<?php

namespace App\Http\Services\CoolNumberShoppingMall;

use App\Http\Model\CoolNumberShoppingMall\CoolNumber;
use App\Http\Model\CoolNumberShoppingMall\UseLog;
use App\Http\Model\CoolNumberShoppingMall\UserScore;
use App\Http\Model\CoolNumberShoppingMall\UserUseLog;
use App\Http\Model\SystemConfig;
use App\Http\Model\User;
use App\Http\Services\CommonServices;
use Illuminate\Http\Request;

class CoolNumberServices extends CommonServices
{
    /**
     * @var CoolNumber
     */
    private $modelCoolNumber;

    /**
     * @var SystemConfig
     */
    private $modelSystemConfig;

    /**
     * @var UserScore
     */
    private $modelUserScore;

    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
        $this->modelCoolNumber = new CoolNumber();
        $this->modelSystemConfig = new SystemConfig();
        $this->modelUserScore = new UserScore();
    }

    /**
     * 靓号列表
     *
     * Created at 2021/12/6 17:44
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param Request $request
     * @return array
     */
    public function search(Request $request): array
    {
        $data = [];
        $data['uuid'] = $request->input('uuid', '');// 靓号uuid
        $data['type'] = $request->input('type', '');// 靓号类型
        $page = intval($request->input('page', 0));//第1页传0
        $pageSize = intval($request->input('limit', 10));//每页多少条
        $data['page'] = $page <= 0 ? 1 : $page;
        $data['limit'] = $pageSize <= 0 ? 10 : $pageSize;
        $where = [];
        if ($data['uuid']) {
            $where['uuid'] = $data['uuid'];
        }

        if ($data['type']) {
            $where['type'] = $data['type'];
        }

        $data['total'] = CoolNumber::query()->where($where)->count();
        $data['list'] = [];
        $data['page_total'] = 1;
        if (!$data['total']) {
            return $data;
        }

        $start = ($data['page'] - 1) * $data['limit'];
        $data['list'] = CoolNumber::query()->where($where)->limit($data['limit'])->offset($start)
            ->orderByDesc('id')->get()->toArray();
        $data['page_total'] = intval(ceil($data['total'] / $data['limit']));
        foreach ($data['list'] as &$item) {
            $item['in_use_tip'] = $item['is_use'] == CoolNumber::IS_USE_NO ? '未使用' : '使用中';
            $item['start_time_tip'] = $item['start_time'] ? date('Y-m-d H:i:s', $item['start_time']) : '';
            $item['expiry_time_tip'] = $item['expiry_time'] ? date('Y-m-d H:i:s', $item['expiry_time']) : '';
        }

        return $data;
    }

    /**
     * 添加靓号
     *
     * Created at 2021/12/6 17:45
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param string $subject
     * @throws \App\Exceptions\PublicException
     */
    public function add(string $uuid)
    {
        $this->modelCoolNumber->add($uuid);
    }

    /**
     * 靓号使用日志
     *
     * Created at 2021/12/6 18:02
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param Request $request
     * @return array
     */
    public function listUseLog(Request $request): array
    {
        $data = [];
        $data['uuid'] = $request->input('uuid', '');// 靓号uuid
        $page = intval($request->input('page', 0));//第1页传0
        $pageSize = intval($request->input('limit', 10));//每页多少条
        $data['page'] = $page <= 0 ? 1 : $page;
        $data['limit'] = $pageSize <= 0 ? 10 : $pageSize;
        $where = [];
        if ($data['uuid']) {
            $where['uuid'] = $data['uuid'];
        }

        $data['total'] = UseLog::query()->where($where)->count();
        $data['list'] = [];
        $data['page_total'] = 1;
        if (!$data['total']) {
            return $data;
        }

        $start = ($data['page'] - 1) * $data['limit'];
        $data['list'] = UseLog::query()->where($where)->limit($data['limit'])->offset($start)->orderByDesc('id')->get()->toArray();
        $data['page_total'] = intval(ceil($data['total'] / $data['limit']));
        $users = collect((new User())->get_users_by_ids(array_unique(array_column($data['list'], 'user_id'))))->keyBy('user_id')->toArray();//获取用户信息
        foreach ($data['list'] as &$item) {
            $userId = $item['user_id'];
            $item['user_nickname'] = $users[$userId]['nickname'] ?? '';
            $item['user_image'] = $users[$userId]['images'][0] ?? '';
            $userGender = $users[$userId]['gender'] ?? '';
            $item['user_gender'] = $userGender == 1 ? '男' : ($userGender == 2 ? '女' : '未知');
            $item['created_at_tip'] = $item['created_at'] ? date('Y-m-d H:i:s', $item['created_at']) : '';
            $item['expiry_time_tip'] = $item['expiry_time'] ? date('Y-m-d H:i:s', $item['expiry_time']) : '';
            $item['is_use_tip'] = $item['expiry_time'] > time() ? '使用中' : '已到期';
        }

        return $data;
    }

    /**
     * 获取基本信息
     *
     * Created at 2021/12/7 17:20
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param int $loginUserId
     * @return array
     */
    public function getBasicInfo(int $loginUserId): array
    {
        return [
            'is_open' => $this->modelSystemConfig->getCoolNumberShoppingMallOpenStatus(),
            'score' => $this->modelUserScore->getUserScore($loginUserId),
            'describe_text' => '使用期在购买后开始计算，购买后请及时前往【我的】【背包】【道具背包】中查看使用已购买的个人靓号道具',
            'rules' => [
                'id' => 1,
                'key' => 'cool_number_mall_goods_rule',
                'content' => '<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=1.0, user-scalable=no">
  <title></title>
</head>
<body>
<h4>怎么 获得靓号积分？会过期吗？</h4>
<p>可以通过官方指定活动获得；靓号积分实用又有效地哦，会伴随着账号一直存在的~</p >
<h4>兑换后如何使用？可以赠送吗？</h4>
<p>兑换后可在【我的】【背包】【道具背包】中查看使用，使用后会立即覆盖当前ID；可以选择赠送给你的好友~</p >
<h4>有效期怎么计算？过期后会怎样？</h4>
<p>兑换成功后，有效期将会进入倒计时，请及时使用哦；过期后会恢复至原始默认ID，当前已有靓号的用户建议不要使用哦~</p >
<h4>为什么有的靓号不能兑换？</h4>
<p>当有的靓号道具已被兑换后，在其过期前，其他人是无法兑换的~</p>
<h4>如有其他疑问，可以联系官方客服~</h4>
</body>
</html>',
                'type' => 1000,
                'title' => '规则说明',
                'created_at' => date('Y-m-d H:i:s'),
            ],
        ];
    }

    /**
     * 使用靓号-更新靓号状态
     *
     * Created at 2021/12/9 10:32
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param string $uuid
     * @param int $expiryTime
     * @return int
     */
    public function beginUseUuid(string $uuid, int $expiryTime): int
    {
        return $this->modelCoolNumber->singleUpdateRaw('uuid="' . $uuid . '" and is_use=' . CoolNumber::IS_USE_NO,
            ['is_use' => CoolNumber::IS_USE_YES, 'start_time' => time(), 'expiry_time' => $expiryTime, 'updated_at' => time()]);
    }

    /**
     * 停止使用靓号-更新靓号状态
     *
     * Created at 2021/12/9 10:34
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param string $uuid
     * @return int
     */
    public function stopUseUuid(string $uuid): int
    {
        return $this->modelCoolNumber->singleUpdateRaw('uuid="' . $uuid . '"',
            ['is_use' => CoolNumber::IS_USE_NO, 'expiry_time' => time(), 'updated_at' => time()]);
    }

    /**
     * 获取靓号类型
     *
     * Created at 2021/12/9 15:04
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @return array
     */
    public function getTypes(): array
    {
        return $this->modelCoolNumber->getTypes();
    }

    /**
     * 用户uuid使用日志
     *
     * Created at 2021/12/6 18:02
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param Request $request
     * @return array
     */
    public function listUuidUserUseLog(Request $request): array
    {
        $data = [];
        $data['user_id'] = intval($request->input('user_id', 0));// 用户user_id
        $page = intval($request->input('page', 0));
        $pageSize = intval($request->input('limit', 10));//每页多少条
        $data['page'] = $page <= 0 ? 1 : $page;
        $data['limit'] = $pageSize <= 0 ? 10 : $pageSize;
        $where['user_id'] = $data['user_id'];
        $data['total'] = UserUseLog::query()->where($where)->count();
        $data['list'] = [];
        $data['page_total'] = 1;
        if (!$data['total']) {
            return $data;
        }

        $start = ($data['page'] - 1) * $data['limit'];
        $data['list'] = UserUseLog::query()->where($where)->limit($data['limit'])->offset($start)->orderByDesc('id')->get()->toArray();
        $data['page_total'] = intval(ceil($data['total'] / $data['limit']));
        foreach ($data['list'] as &$item) {
            $item['created_at_tip'] = $item['created_at'] ? date('Y-m-d H:i:s', $item['created_at']) : '';
            $item['expiry_time_tip'] = $item['expiry_time'] ? date('Y-m-d H:i:s', $item['expiry_time']) : '';
            $item['is_use'] = intval($item['expiry_time'] > time());
            $item['change_mode_tip'] = $item['change_mode'] == UserUseLog::CHANGE_AUTO ? '自动' : '手动';
        }

        return $data;
    }

    /**
     * 获取未被使用的靓号
     *
     * Created at 2021/12/9 16:44
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @return array
     */
    public function listNotUseCoolNumber(): array
    {
        return $this->modelCoolNumber->getSingle(['usage_times' => 0], ['id', 'uuid']);
    }
}